package com.sxx.mall.order.web;

import com.sxx.commons.exception.NoStockException;
import com.sxx.mall.order.service.OrderService;
import com.sxx.mall.order.vo.OrderConfirmVO;
import com.sxx.mall.order.vo.OrderItemVO;
import com.sxx.mall.order.vo.OrderResponseVO;
import com.sxx.mall.order.vo.OrderSubmitVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Auther: sunxx
 * @Date: 2024/9/4 - 09 - 04 - 13:29
 * @Description: com.sxx.mall.order.web
 * @version: 1.0
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model){
        //TODO 查询订单信息，收货地址
        OrderConfirmVO orderConfirmVO = orderService.confirmOrder();
        model.addAttribute("confirmVO",orderConfirmVO);
        return "confirm";
    }

    @PostMapping("/orderSubmit")
    public String orderSubmit(OrderSubmitVO vo, Model model, RedirectAttributes redirectAttributes){
        Integer code = 0;
        OrderResponseVO responseVO = null;
        try {
            responseVO = orderService.submitOrder(vo);
        }catch (NoStockException e){
            e.printStackTrace();
        }
        if (responseVO.getCode() != 0){
            code = responseVO.getCode();
            System.out.println("下单失败：code:"+code);
            String msg = "下单失败";
            if (code == 1){
                msg = msg + ":重复提交";
            }else if (code == 2){
                msg = msg + ":锁定库存失败";
            }
            redirectAttributes.addAttribute("msg",msg);
            //redirectAttributes.addFlashAttribute("msg",msg);
            //下单失败
            return "redirect:http://order.jiaxuanmall.aisa:8030/toTrade";
        }
        //表示下单成功
        model.addAttribute("orderResponseVO",responseVO);
        return "pay";
    }

}
